package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Transactional
    @Override
    public void saveWithFlavors(DishDto dishDto) {
        //保存菜品以及口味的代码

        //①. 保存菜品基本信息 ;
        this.save(dishDto); //仅仅只是保存菜品的数据
        //②. 获取保存的菜品ID ;
        Long dishId = dishDto.getId();
        //③. 获取菜品口味列表，遍历列表，为菜品口味对象属性dishId赋值;
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
            //④. 批量保存菜品口味列表;
            dishFlavorService.save(flavor);
        }

    }

    @Override
    public DishDto getByIDWithFlavor(Long id) {
        //根据菜品ID查询菜品信息  dish
        Dish dish=this.getById(id);
        //创建dishDto对象
        DishDto dishDto=new DishDto();
        //将dish数据复制到dishDto对象
        BeanUtils.copyProperties(dish,dishDto);
        //从dish_flavor中根据菜品ID查询口味信息
        //SELECT *  FROM dish_flavor WHERE dish_id='xxx'
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dish.getId());// WHERE dish_id='xxx'
        List<DishFlavor> list = dishFlavorService.list(lqw);
        //将口味封装到dishDto对象上
        dishDto.setFlavors(list);
        //返回dishDto对象
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavors(DishDto dishDto) {
        //跟新菜品表的数据
        this.updateById(dishDto);

        //DELETE FROM dish_flavor WHERE id=222
        //INSERT INTO dish_flavor VALUES('id','ixx',xxx);
        //INSERT INTO dish_flavor VALUES('id','ixx',xxx);
        //INSERT INTO dish_flavor VALUES('id','ixx',xxx);
        //跟新口味表的数据

        //清理当前菜品对应口味数据---dish_flavor表的delete操作
        LambdaQueryWrapper<DishFlavor> lqw1=new LambdaQueryWrapper<>();
        lqw1.eq(DishFlavor::getDishId,dishDto.getId());//WHERE id=222
        dishFlavorService.remove(lqw1);
        //添加当前提交过来的口味数据---dish_flavor表的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        //批量保存口味数据
        dishFlavorService.saveBatch(flavors);
    }
}
